import { createContext, useState, useEffect, useContext } from 'react';
import { isAuthenticated, adminLogin, logout, getAuthInfo, getStoreByPhone } from '../services/pocketBaseService';

// 创建认证上下文
const AuthContext = createContext();

// 认证提供器组件
export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  // 检查登录状态
  useEffect(() => {
    const checkAuth = async () => {
      const authInfo = getAuthInfo();
      if (authInfo.isValid) {
        setUser({ isAdmin: true, store: null });
      } else {
        setUser(null);
      }
      setLoading(false);
    };
    checkAuth();
  }, []);

  // 登录方法，支持store参数
  const login = async (email, password, phone, storeId, storeObj) => {
    setLoading(true);
    // 先管理员登录
    const result = await adminLogin(email, password);
    console.log('管理员登录结果:', result);
    if (result.success) {
      // 登录成功后校验手机号
      let store = null;
      if (storeObj) {
        store = storeObj;
      } else {
        const storeResult = await getStoreByPhone(phone);
        console.log('storeResult', storeResult);
        if (storeResult.success && Array.isArray(storeResult.data?.items)) {
          console.log('storeResult.data.items', storeResult.data.items);
          if (storeId) {
            console.log('storeId', storeId);
            store = storeResult.data.items.find(s => s.id === storeId) || null;
          } else {
            store = storeResult.data.items[0] || null;
          }
        }
      }
      if (store) {
        setUser({ isAdmin: true, store });
        setLoading(false);
        return { success: true };
      } else {
        // 手机号无效，登出
        logout();
        setUser(null);
        setLoading(false);
        return { success: false, error: '未找到对应店铺，请检查手机号' };
      }
    } else {
      setUser(null);
      setLoading(false);
      return { success: false, error: result.error };
    }
  };

  // 登出方法
  const handleLogout = () => {
    logout();
    setUser(null);
  };

  // 提供认证上下文值
  const value = {
    user,
    loading,
    login,
    logout: handleLogout,
    isAuthenticated: !!user,
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

// 自定义钩子，便于组件访问认证上下文
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth必须在<AuthProvider>内部使用');
  }
  return context;
};